<template>
  <div class="watch-demo4">
    <h1>情况四:监视【reactive】定义的【对象类型】数据</h1>
    <h2>姓名：{{ person.name }}</h2>
    <h2>年龄：{{ person.age }}</h2>
    <h2>汽车：{{ person.car.c1 }},{{ person.car.c2 }}</h2>
    <button @click="changeName">修改名字</button>
    <button @click="changeAge">修改年龄</button>
    <button @click="changeCar1">修改第一台车</button>
    <button @click="changeCar2">修改第二台车</button>
    <button @click="changeAllCar">修改所有车</button>
  </div>
</template>

<script lang="ts" setup name="WatchDemo4">
import { reactive, watch } from "vue";
let person = reactive({
  name: "张三",
  age: 18,
  car: {
    c1: "奔驰",
    c2: "宝马",
  },
});
function changeName() {
  person.name += "~";
}
function changeAge() {
  person.age += 1;
}
function changeCar1() {
  person.car.c1 += "~";
}
function changeCar2() {
  person.car.c2 += "~";
}
function changeAllCar() {
  person.car = { c1: "五菱", c2: "蔚来" };
}

//默认开启了深度监听,监听整个对象，无法查看旧值
watch(person, (newValue, oldValue) => {
  console.log(`person发生了变化`, newValue, oldValue);
});
//监听响应式对象中的单个属性,且该属性时基本数据类型的，要写成函数式，可以查看新旧的值
watch(
  () => {
    return person.name;
  },
  (newValue, oldValue) => {
    console.log(`person.name发生了变化`, newValue, oldValue);
  }
);
//监听单个属性,可以查看新旧的值
watch(
  () => {
    return person.age;
  },
  (newValue, oldValue) => {
    console.log(`person.age`, newValue, oldValue);
  }
);
//监听对象
// watch(person.car, (newValue, oldValue) => {
//   console.log(`person的car发生了变化`, newValue, oldValue);
// });
//监听,对象的属性，不管是基本数据类型还是对象类型，都用函数式
watch(
  () => {
    return person.car;
  },
  (newValue, oldValue) => {
    console.log(`person.car`, newValue, oldValue);
  },
  //想监听对象中的属性，需要开启深度监听
  { deep: true }
);
//想要知道旧值，则监听目标属性
watch(
  () => {
    return person.car.c1;
  },
  (newValue, oldValue) => {
    console.log(`person.car.c1`, newValue, oldValue);
  }
);
watch(
  () => {
    return person.car.c2;
  },
  (newValue, oldValue) => {
    console.log(`person.car.c2`, newValue, oldValue);
  }
);
</script>

<style>
.watch-demo4 {
  background-color: skyblue;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;
}
</style>